import { IFlyResData, IHospitalGuestData } from "../../../Script/Interface/IMessage";
import AudioManager, { ESoundType } from "../../../Script/Util/AudioManager";
import BaseSprite from "../../Base/BaseSprite";
import { EResType } from "../../Common/Enum";
import { GlobalData } from "../../Common/GlobalData";
import { SceneGame } from "../../SceneGame";
import GameUtil from "../../Util/GameUtil";
import StorageUtil from "../../Util/StorageUtil";
import HospitalUI, { EItemType } from "./HospitalUI";

const { ccclass, property } = cc._decorator;

const MAX_WIDTH: number = 70;
const MAX_HEIGHT: number = 120;
const DISTANCE: number = 180;   // 顾客间距

@ccclass
export default class HospitolGuest extends BaseSprite {

    @property({ type: cc.Node, tooltip: "人物" })
    private skes: cc.Node = null;

    @property({ type: cc.Node, tooltip: "气泡" })
    private bubble: cc.Node = null;

    @property({ type: cc.Node, tooltip: "锁子" })
    private lock: cc.Node = null;

    private isMove: boolean = false;

    private data: IHospitalGuestData = null;
    private ske: sp.Skeleton = null;

    protected onEnable(): void {
        this.lock.on(cc.Node.EventType.TOUCH_END, this.onLockBtnClicked, this);
        this.bubble.on(cc.Node.EventType.TOUCH_END, this.onBubbleBtnClicked, this);
    }

    protected onDisable(): void {
        this.lock.off(cc.Node.EventType.TOUCH_END, this.onLockBtnClicked, this);
        this.bubble.off(cc.Node.EventType.TOUCH_END, this.onBubbleBtnClicked, this);
    }

    public setData(data: IHospitalGuestData) {
        this.data = data;
        if (!data.isLock && data.itemId < 0) {
            data.itemId = HospitalUI.instance.getItemIdBySurface();
        }

        this.lock.active = data.isLock;
        this.bubble.scale = 0;
        this.node.x = !data.isLock ? 600 + DISTANCE * data.guestId : -240 + DISTANCE * data.guestId; // 已解锁?屏外:停止
        this.node.active = data.itemId != null;

        this.skes.children.forEach((o) => {
            o.active = false;
        });
        const index = Math.floor(Math.random() * this.skes.children.length);
        const node = this.skes.children[index];
        node.active = true;
        this.ske = node.getComponent(sp.Skeleton);
        this.ske.setAnimation(0, 'daiji', true);
        if (data.isLock) {
            node.color = cc.color().fromHEX('#717171');
        } else {
            node.color = cc.color().fromHEX('#FFFFFF');
            this.guestCome();
        }
    }

    public refreshUI() {
        if (!this.data) return;
        if (this.data.cur >= this.data.max) {
            // 顾客需求完成后设置成-1，防止重复添加
            this.data.itemId = -1;
            // 刷新新手引导的小手
            HospitalUI.instance.curItemId = -1;

            setTimeout(() => {
                if (this.ske && this.bubble) {
                    this.ske.setAnimation(0, 'daiji', true);
                    this.bubble.stopAllActions();
                    cc.tween(this.bubble).sequence(
                        cc.scaleTo(0.2, 0),
                        cc.delayTime(0.3),
                        cc.callFunc(() => {
                            this.guestGo();
                        }),
                    ).start();
                }
            }, 1000);
        }

        this.updateColor();
    }

    private guestCome() {
        if (!this.data || this.data.isLock) {
            return;
        }

        this.isMove = true;
        this.node.x = 600 + DISTANCE * this.data.guestId;
        this.node.stopAllActions();
        cc.tween(this.node).sequence(
            cc.delayTime(0.2 * this.data.guestId),
            cc.moveTo(0.7, cc.v2(-240 + DISTANCE * this.data.guestId, this.node.y)).easing(cc.easeBackIn()),
            cc.callFunc(() => {
                this.showBubble();
            }),
        ).start();
    }

    private guestGo() {
        AudioManager.instance.playSound(ESoundType.HospitalGuestComplete);
        this.node.stopAllActions();
        cc.tween(this.node).sequence(
            cc.moveTo(0.3, cc.v2(-600, this.node.y)),
            cc.callFunc(() => {
                this.data.cur = 0;
                this.data.itemId = HospitalUI.instance.getItemIdBySurface();
                this.data.skeId = Math.floor(Math.random() * 6);
                this.refreshBubble();

                this.node.active = this.data.itemId != null;
                // this.guestCome();
                this.setData(this.data);

                // 刷新进度条
                HospitalUI.instance.refreshProgress(true);
            }),
        ).start();

        // 获得奖励
        this.flyReward();
    }

    private flyReward() {
        const hospitalData = StorageUtil.instance.getHospitalData();
        const config = GlobalData.getHospitalConfig(hospitalData.id);
        if (config) {
            const data = SceneGame.instance.getFlyResData();
            const flyData: IFlyResData = {
                resType: EResType.Money,
                parent: data.flyNode,
                from: this.bubble,
                to: data.money,
                value: config.reward,
                flyTimes: 10,
                maxWidth: 60,
                maxHeight: 60,
            }
            GameUtil.instance.flyResIcon(flyData);
        }
    }

    private showBubble() {
        this.isMove = false;
        this.bubble.stopAllActions();
        cc.tween(this.bubble).sequence(
            cc.scaleTo(0.3, 0.7, 0.7).easing(cc.easeBackInOut()),
            cc.callFunc(() => {
                this.refreshBubble();
                // 暂存区到顾客
                HospitalUI.instance.tempToGuest(this.data.itemId);
            }),
        ).start();
    }

    private refreshBubble() {
        this.bubble.children.forEach((o, i) => {
            const cb = () => {
                o.stopAllActions();
                cc.tween(o).repeatForever(
                    cc.sequence(
                        cc.scaleTo(1, o.scale * 1.2, o.scale * 1.2).easing(cc.easeSineOut()),
                        cc.scaleTo(1, o.scale * 1, o.scale * 1).easing(cc.easeSineIn()),
                    ),
                ).start();
            }
            const sprite = o.getComponent(cc.Sprite);
            HospitalUI.instance.setItemIcon(EItemType.Guest, this.data.itemId, sprite, MAX_WIDTH, MAX_HEIGHT, cb);
        });

        this.updateColor();
    }

    private updateColor() {
        if (!this.data) return;
        try {
            this.bubble.children.forEach((o, i) => {
                const color = HospitalUI.instance.getColorByState(i < this.data.cur);
                o.color = new cc.Color().fromHEX(color);
            });
        } catch (error) {
            console.log(error, this.data.guestId);
        }
    }

    public getFlyToNode() {
        if (!this.data) return;

        const node = this.bubble.children[this.data.cur];
        this.data.cur++;
        if (this.data.cur > this.data.max) {
            return null;
        }
        return node;
    }

    public getIsMove() {
        return this.isMove;
    }

    private onBubbleBtnClicked(event: cc.Event, data: cc.Event.EventCustom) {
        if (this.isMove) {
            console.log("移动中点击无效!!!");
            return;
        }

        AudioManager.instance.playSound(ESoundType.Click);

        HospitalUI.instance.shakeTip(this.data.itemId);
    }

    private isClick: boolean = true;
    private onLockBtnClicked(event: cc.Event, data: cc.Event.EventCustom) {
        AudioManager.instance.playSound(ESoundType.Click);
        if (this.data.isLock) {
            this.data.itemId = HospitalUI.instance.getItemIdBySurface();
            this.data.isLock = false;
            this.setData(this.data);

            // if (!this.isClick) {
            //     return;
            // }
            // this.isClick = false;
            // AdManager.reportVideo(EVideoType.Unlock, DATA.id, DATA.name);
            // AdManager.showVideoAd(() => {
            //     this.isClick = true;
            //     AdManager.reportOverVideo(DATA.id, DATA.name);
            //     this.data.itemId = HospitalUI.instance.getItemIdBySurface();
            //     this.data.isLock = false;
            //     this.setData(this.data);
            // }, () => {
            //     this.isClick = true;
            // })
        }
    }
}